<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Db;

/**
 * 借、赠 - 操作
 * Class
 * @package
 */
class Borrmoney extends Api
{
	protected $noNeedLogin = ['lists'];
	protected $noNeedRight = '*';


	/**
	 * 限制赠借款
	 */
	public function limit_borr()
	{
		$uid = $this->auth->id;
		// $uid = 13;
		$ret = 1;
		$limit_ids = [2, 5, 6, 10, 12];
		if (in_array($uid, $limit_ids)) {
			$ret = 0;
		}
		$this->success("成功", $ret);
	}

	/**
	 * 是否有赠、借记录
	 */
	public function check_borrow()
	{
		$uid = $this->auth->id;
		// $uid = 13;
		$limit_ids = [2, 5, 6, 10, 12];
		if (in_array($uid, $limit_ids)) {
			$this->error("禁止操作！！！");
		} else {
			$check_borrow = \app\api\controller\basics\Basics::instance()->check_borrow_not_return($uid);
			$ret = 0;
			if ($check_borrow) {
				$ret = 1;
			}
			$this->success("成功", $ret);
		}
	}

	/**
	 * 赠、借列表
	 */
	public function lists()
	{
		$uid = $this->auth->id;
		$limit = 10;
		$page =  $this->request->post("page");
		// 1  赠送、借出  2 获赠、借入
		$display_tp = $this->request->post("distyp");
		// 类 J 借 Z 赠
		$t = $this->request->post("typ");
		// bid   借K人
		// loan_id  放K人
		$data = [];
		$offset = ($page - 1) * $limit;
		$where = "typs = '{$t}' and ";
		$where .= ($display_tp == 1 ?  "loan_id = " . $uid : ($display_tp == 2 ?  "bid = " . $uid : "bid = 0"));

		$field = "typs,case typs when 'J' then '借' when 'Z' then '赠' end typsNick";
		$field .= ",repay,case repay when 1 then '已还' when 2 then '未还' end repayNick";
		$field .= ",from_unixtime(create_time,'%Y-%m-%d %H:%i:%s') ctime";
		$field .= ",ifnull(from_unixtime(repay_time,'%Y-%m-%d %H:%i:%s'),0) rtime";

		$req = Db::name("balance_borrow")
			->where($where)
			->field("id,bid,loan_id,money," . $field)
			->order("repay DESC,create_time DESC")
			->limit((int)$offset, $limit)
			->select();

		if ($req) {
			foreach ($req as $k => $v) {
				$id = 0;
				$id = ($display_tp == 1 ?  $v["bid"] : ($display_tp == 2 ?  $v["loan_id"] : 0));
				$data[] = $v;
				$data[$k]["phone"] = \app\api\controller\basics\Basics::instance()->get_user_nickname($id);
				$data[$k]["balance"] = $this->_get_loan_balance($v["bid"]);
			}
		}

		if ($display_tp == 2 && $t == 'J') {
			$cap = Db::name("works_cap")
				->where("user_id", $uid)
				->field("id,user_id bid,money,repayMoney,typs,repay_typs,case repay_typs when 1 then '运营资金' when 2 then '机具款'  end rtNick,case typs when 'J' then '借' when 'Z' then '赠' end typsNick,is_repay repay,case is_repay when 1 then '已还' when 2 then '还款中' when 3 then '未还' end repayNick,from_unixtime(create_time,'%Y-%m-%d %H:%i:%s') ctime,from_unixtime(repay_time,'%Y-%m-%d %H:%i:%s') rtime")
				->select();
			if ($cap) {
				for ($i = 0; $i < count($cap); $i++) {
					$sub = bcsub((string) $cap[$i]['money'], (string)$cap[$i]["repayMoney"], 2);
					$cap[$i]["id"] = $cap[$i]["id"] . "_JIN";
					$cap[$i]["phone"] = $cap[$i]["rtNick"] . ($cap[$i]["repay"] == 1 ? "" : "：已还[" . $cap[$i]["repayMoney"] . "]-未还[" . $sub . "]");
					$cap[$i]["balance"] = $this->_get_loan_balance($cap[$i]["bid"]);
				}
			}
			$data = array_merge($cap, $data);
		}

		$this->success("正常", $data);
	}

	/**
	 * 还款
	 */
	public function repay()
	{
		$id = $this->request->post("ids");
		if (!empty($id)) {
			$con = explode("_", $id);
			if (count($con) > 1) {
				$this->error("运营资金，禁止手动还款操作！！！");
			} else {
				$req = \app\api\controller\basics\Basics::instance()->get_borrow_info($id);
				if ($req) {
					if ($req["repay"] == 1) {
						$this->error("该订单已还！！！");
					} else {
						$balance = $this->_get_loan_balance($req["bid"]);
						if ($req["money"] > $balance) {
							$this->error("余额不足，失败！！！");
						} else {
							$flag = false;
							$subOption = [];
							$addCordsReq = [];
							Db::startTrans();
							$updata_reqy_option = ["repay" => 1, "repay_time" => time()];
							$ret = Db::name("balance_borrow")
								->where("id= " . $req["id"])
								->update($updata_reqy_option);
							if ($ret) {
								$subOption = [
									"uid"		=> $req["bid"], 	// 支出 代理ID
									"typs"		=> 5, 				// 变更类型 5=还款
									"isChg" 	=> 2, 				// 2 支出
									"remark" 	=>  "给" . \app\api\controller\basics\Basics::instance()->get_user_name($req["loan_id"]) . "还",	// 备注  => 没有备注传空字符串
									"chgAmt" 	=> $req["money"],	// 变更金额
									"ids" 		=> $req["id"],		// 操作订单主ID 
								];
								$subReq = \app\common\controller\Balance::instance()->sub_and_logs($subOption);
								if ($subReq) {
									$add_before = \app\common\controller\Balance::instance()->get($req["loan_id"]);
									$add_after  = $req["money"];
									if ($add_before > 0) $add_after = bcadd((string)$add_before, (string) $req["money"], 2);
									$addOption = [
										"uid"		=> $req["loan_id"], // 收入 或  代理ID
										"typs"		=> 5, 				// 变更类型 5=还款
										"isChg" 	=> 1, 				// 1 收入
										"remark" 	=> \app\api\controller\basics\Basics::instance()->get_user_name($req["bid"]) . "给还入",	// 备注  => 没有备注传空字符串
										"orig"		=> $add_before, 	// 原余额    => 默认传0
										"chgAmt" 	=> $req["money"],	// 变更金额
										"after"		=> $add_after,  	// 变更后余额
										"ids" 		=> $req["id"],		// 操作订单主ID 
									];
									$addCordsReq = \app\common\controller\Balance::instance()->cords($addOption);
									if ($addCordsReq) {
										// 受益人 - 增余额
										\app\api\controller\basics\Basics::instance()->repay_add_balance($req["loan_id"], $req["money"]);
										// 是否 借款已还清 - 可否解冻提现
										\app\api\controller\basics\Basics::instance()->repay_unlock_cash_out($req["bid"]);
										$flag = true;
										Db::commit();
									}
								}
							}
							if ($flag) {
								$this->success("操作成功", 1);
							} else {
								$this->error("操作失败");
								Db::rollback();
							}
						}
					}
				} else {
					$this->error("信息有误！！！");
				}
			}
		}
		$this->error("参数有误");
	}

	/**
	 * 借、赠款进件
	 */
	public function borrow()
	{
		$uid = $this->auth->id;
		// 借或增 人
		$cid = $this->request->post("childID");
		// 类 J 借 Z 增
		$t = $this->request->post("typ");
		// 数
		$m = $this->request->post("money");

		$limit_ids = [2, 5, 6, 10, 12];
		if (in_array($uid, $limit_ids)) {
			$this->error("禁止操作！！！");
		} else {
			$loan_money = $this->_get_loan_balance($uid);
			if (!empty($cid) && !empty($t) && !empty($m)) {
				if ($t == 'J' || $t == 'Z') {
					$nick = ($t == 'J' ? "借" : ($t == 'Z' ?  "赠" : "其他"));
					$format_nums = ($t == 'J' ? 4 : ($t == 'Z' ?  6 : "其他"));
					$ck_borr = false;
					if ($t == 'Z') {
						$ck_borr = \app\api\controller\basics\Basics::instance()->check_borrow_not_return($uid);
					}
					if ($ck_borr) {
						$this->error("您有借未还记录，不可向下级" . $nick);
					} else {
						if ($m > $loan_money) {
							$this->error("您的金额不足，{$nick}失败！！！");
						} else {
							$check_rela = \app\api\controller\basics\Basics::instance()->check_under($uid, $cid);
							if ($check_rela === false) {
								$this->error("与该代理不是直属关系，请谨慎操作！！！");
							} else {
								Db::startTrans();
								$flag = false;
								$option = [];
								$changeBalanceOption = [];
								$option = [
									"bid" => $cid,
									"loan_id" => $uid,
									"money" => $m,
									"typs"  => $t,
									"repay" => ($t == 'J' ? 2 : ($t == 'Z' ?  1 : 0)),
									"create_time" => time()
								];
								$id = Db::name("balance_borrow")->insertGetId($option);
								if ($id) {
									$changeBalanceOption = [
										"aid"		=> $option["bid"], 		// 增 - 代理ID
										"sid"		=> $option["loan_id"], 	// 减 - 代理ID
										"typs"		=> $format_nums, 		// 变更类型 4=借款,6=赠送
										"isChg" 	=> "1_2", 				// 1 收入 2 支出 传 顺序 => 加_减[1_2]
										"remark" 	=>  \app\api\controller\basics\Basics::instance()->get_user_name($uid) . "给" . $nick . "入" . "_给" . \app\api\controller\basics\Basics::instance()->get_user_name($cid) . "" . $nick . "出",	// 备注  => 加减顺序 下划线 (_) 隔开 如：加_减
										"chgAmt" 	=> $option["money"],	// 变更金额
										"ids" 		=> $id,					// 操作订单主ID
									];
									$req = \app\common\controller\Balance::instance()->comp_and_log($changeBalanceOption);
									if ($req) {
										if ($t == 'J') {
											\app\api\controller\basics\Basics::instance()->lock_withdraw($cid);
										}
										Db::commit();
										$flag = true;
									}
								}
								if ($flag) {
									$this->success("操作成功", 1);
								} else {
									$this->error("操作失败");
									Db::rollback();
								}
							}
						}
					}
				} else {
					$this->error("操作类型有误，请重新确认！！！");
				}
			} else {
				$this->error("提交信息异常，核对请重新提交！！！");
			}
		}
	}

	/**
	 * 借米人查找
	 */
	public function childs_list()
	{
		$uid = $this->auth->id;
		$phone = $this->request->post("phone");
		$tab = "user";
		$finds = Db::name($tab)
			->where("pid = " . $uid  . " and mobile = {$phone}")
			->field("id,mobile")
			->find();
		if ($finds) {
			$this->success("正常", $finds);
		} else {
			$this->error("代理未找到，重新查找");
		}
	}

	/**
	 * 放米人 - 余额
	 */
	protected function _get_loan_balance($uid)
	{
		$balance = 0;
		if ($uid) {
			$where = "";
			$where = "main_id = " . $uid;
			$check = Db::name("balance")
				->where($where)
				->count();
			if ($check) {
				$balance = Db::name("balance")->where($where)->value("money");
			}
		}
		return $balance;
	}
}
